import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Roles } from './roles.decorator';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    console.log(context.getHandler());
    // 获取到对应接口方法设置的的身份 例如: @Roles(['admin'])中的 ['admin']
    const roles = this.reflector.get(Roles, context.getHandler());
    console.log(roles);

    if (!roles) {
      return true;
    }
    const request = context.switchToHttp().getRequest();
    const user = request.user;
    // 这里可以根据用户的角色进行判断
    // return roles.includes(user.role);
    return true;
  }
}
